<template>
  <div class="products-container">
    <div class="header-section">
      <h1>保险金融产品</h1>
      <p>为您提供全面的保险和金融解决方案</p>
    </div>

    <!-- 搜索和过滤区域 -->
    <div class="filters-section">
      <div class="search-box">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索产品名称..."
          @keyup.enter="searchProducts"
        >
        <button @click="searchProducts">
          <i class="search-icon">🔍</i>
        </button>
      </div>

      <div class="category-filter">
        <select v-model="selectedCategory" @change="filterByCategory">
          <option value="">所有分类</option>
          <option v-for="category in categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载产品中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <p>⚠️ 加载产品失败: {{ error }}</p>
      <button @click="fetchProducts">重试</button>
    </div>

    <!-- 空状态提示 -->
    <div v-if="products.length === 0 && !loading" class="empty-state">
      <p>没有找到匹配的产品</p>
      <button @click="resetFilters">重置筛选条件</button>
    </div>

    <!-- 产品网格 -->
    <div class="products-grid">
      <div
        class="product-card"
        v-for="product in products"
        :key="product.id"
        @click="viewProductDetail(product.id, product.category.id)"
      >
        <div class="product-image">
          <img
            v-if="product.img_url"
            :src="'http://127.0.0.1:8000/uploads/'+product.img_url"
            :alt="product.name"
            class="product-img"
            @error="handleImageError"
          >
          <div v-else class="image-placeholder">
            {{ product.category.is_financial ? '💰' : '📄' }}
          </div>
        </div>
        <div class="product-info">
          <div class="card-header">
            <h3>{{ product.name }}</h3>
            <span class="category-tag">{{ product.category_name }}</span>
          </div>
          <p class="product-type">{{ getProductType(product) }}</p>
          <div class="insurance-details">
            <div v-if="product.premium" class="detail-item">
              <span class="detail-label">保费:</span>
              <span class="detail-value">¥{{ product.premium }}</span>
            </div>
            <div v-if="product.coverage_amount" class="detail-item">
              <span class="detail-label">保额:</span>
              <span class="detail-value">¥{{ formatAmount(product.coverage_amount) }}</span>
            </div>
            <div v-if="product.coverage_period" class="detail-item">
              <span class="detail-label">期限:</span>
              <span class="detail-value">{{ product.coverage_period }}</span>
            </div>
            <div v-if="product.annual_return" class="detail-item">
              <span class="detail-label">年化收益:</span>
              <span class="detail-value">{{ product.annual_return }}%</span>
            </div>
          </div>
          <div class="risk-level" :class="getRiskClass(product.risk_level)">
            风险等级: {{ getRiskText(product.risk_level) }}
          </div>
          <div class="target-audience" v-if="product.target_audience">
            适用人群: {{ product.target_audience }}
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="totalPages > 1" class="pagination">
      <button
        @click="changePage(currentPage - 1)"
        :disabled="currentPage === 1"
      >
        &laquo; 上一页
      </button>

      <button
        v-for="page in pages"
        :key="page"
        @click="changePage(page)"
        :class="{ active: currentPage === page }"
      >
        {{ page }}
      </button>

      <button
        @click="changePage(currentPage + 1)"
        :disabled="currentPage === totalPages"
      >
        下一页 &raquo;
      </button>

      <div class="page-info">
        第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "ProductsView",
  data() {
    return {
      products: [],
      categories: [],
      loading: false,
      error: null,
      searchQuery: '',
      selectedCategory: '',
      currentPage: 1,
      pageSize: 9,
      totalPages: 0,
      totalProducts: 0
    };
  },
  computed: {
    pages() {
      const pages = [];
      const start = Math.max(1, this.currentPage - 2);
      const end = Math.min(this.totalPages, this.currentPage + 6);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      return pages;
    }
  },
  watch: {
    currentPage() {
      this.fetchProducts();
    }
  },
  mounted() {
    this.fetchProducts();
    this.fetchCategories();
  },
  methods: {
    async fetchProducts() {
      this.loading = true;
      this.error = null;

      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          name: this.searchQuery,
          category: this.selectedCategory
        };

        // 使用搜索API端点
        const response = await axios.get('http://127.0.0.1:8000/goods/search/', { params });

        // 使用后端返回的分页数据
        this.products = response.data.results;
        this.totalProducts = response.data.count;
        this.totalPages = response.data.total_pages;

      } catch (err) {
        console.error('获取产品失败:', err);
        this.error = err.response?.data?.detail || err.message || '服务器错误';
      } finally {
        this.loading = false;
      }
    },

    async fetchCategories() {
      try {
        const response = await axios.get('http://127.0.0.1:8000/goods/categories/');
        this.categories = response.data;
      } catch (err) {
        console.error('获取分类失败:', err);
      }
    },

    searchProducts() {
      this.currentPage = 1;
      this.fetchProducts();
    },

    filterByCategory() {
      this.currentPage = 1;
      this.fetchProducts();
    },

    resetFilters() {
      this.searchQuery = '';
      this.selectedCategory = '';
      this.currentPage = 1;
      this.fetchProducts();
    },

    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    },

    viewProductDetail(productId) {
      this.$router.push({ name: 'product-detail', params: { id: productId} });
    },

    formatAmount(amount) {
      if (amount >= 1000000) {
        return (amount / 1000000).toFixed(1) + '百万';
      } else if (amount >= 10000) {
        return (amount / 10000).toFixed(1) + '万';
      }
      return amount;
    },

    getProductType(product) {
      if (product.premium && product.coverage_amount) {
        return '保险产品';
      } else if (product.annual_return) {
        return '金融产品';
      }
      return '一般产品';
    },

    getRiskClass(level) {
      return {
        'low': 'risk-low',
        'medium': 'risk-medium',
        'high': 'risk-high'
      }[level] || 'risk-medium';
    },

    getRiskText(level) {
      return {
        'low': '低风险',
        'medium': '中风险',
        'high': '高风险'
      }[level] || '中风险';
    },

    // 图片加载错误处理
    handleImageError(event) {
      const placeholder = event.target.parentElement.querySelector('.image-placeholder');
      if (placeholder) {
        event.target.style.display = 'none';
        placeholder.style.display = 'flex';
      } else {
        event.target.parentElement.innerHTML = `
          <div class="image-placeholder">
            ${event.target.alt ? event.target.alt.charAt(0) : '📄'}
          </div>
        `;
      }
    }
  }
}
</script>

<style scoped>
.products-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
  background-color: #f8f9fc;
}

.header-section {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px;
  background: linear-gradient(135deg, #2e59d9 0%, #4e73df 100%);
  border-radius: 10px;
  color: white;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

.header-section h1 {
  font-size: 2.5rem;
  margin-bottom: 15px;
  font-weight: 700;
}

.header-section p {
  font-size: 1.2rem;
  max-width: 700px;
  margin: 0 auto;
  opacity: 0.9;
}

.filters-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 20px;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.search-box {
  display: flex;
  flex: 1;
  max-width: 500px;
}

.search-box input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 1rem;
  border-right: none;
}

.search-box button {
  padding: 0 20px;
  background: #4e73df;
  color: white;
  border: 1px solid #4e73df;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: background 0.3s;
}

.search-box button:hover {
  background: #2e59d9;
}

.category-filter select {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  min-width: 200px;
  background: white;
  cursor: pointer;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
  margin-top: 20px;
}

.product-card {
  border: 1px solid #eaeaea;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: #fff;
  box-shadow: 0 3px 10px rgba(0,0,0,0.08);
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.12);
  border-color: #4e73df;
}

.product-image {
  height: 200px;
  overflow: hidden;
  background: linear-gradient(120deg, #f6f9ff 0%, #eef2f7 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-img {
  transform: scale(1.05);
}

.financial-icon {
  font-size: 4rem;
  color: #4e73df;
  opacity: 0.2;
}

.image-placeholder {
  font-size: 3rem;
  color: #d1d3e2;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 20px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  font-size: 1.25rem;
  color: #2e384d;
  flex: 1;
  font-weight: 600;
}

.category-tag {
  background-color: #4e73df;
  color: white;
  padding: 4px 10px;
  border-radius: 15px;
  font-size: 0.8rem;
  font-weight: 500;
}

.product-type {
  color: #6e707e;
  font-size: 0.9rem;
  font-weight: 500;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}

.insurance-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 0.95rem;
}

.detail-label {
  color: #6e707e;
  font-weight: 500;
}

.detail-value {
  color: #2e384d;
  font-weight: 600;
}

.risk-level {
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 0.85rem;
  font-weight: 500;
  text-align: center;
  margin-top: auto;
  margin-bottom: 10px;
}

.risk-low {
  background-color: #e6f4ea;
  color: #28a745;
}

.risk-medium {
  background-color: #fff8e1;
  color: #f6c23e;
}

.risk-high {
  background-color: #fce8e6;
  color: #e74a3b;
}

.target-audience {
  font-size: 0.85rem;
  color: #6e707e;
  padding-top: 10px;
  border-top: 1px dashed #eaeaea;
  margin-top: 10px;
}

.loading-spinner {
  text-align: center;
  padding: 60px 0;
}

.spinner {
  border: 4px solid rgba(78, 115, 223, 0.1);
  border-left-color: #4e73df;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  background-color: #fce8e6;
  color: #e74a3b;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  margin: 30px 0;
}

.error-message p {
  margin-bottom: 15px;
  font-weight: 500;
}

.error-message button {
  background-color: #e74a3b;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.3s;
}

.error-message button:hover {
  background-color: #c23a2d;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background: white;
  border-radius: 10px;
  box-shadow: 0 3px 10px rgba(0,0,0,0.05);
}

.empty-state p {
  font-size: 1.2rem;
  color: #6e707e;
  margin-bottom: 20px;
}

.empty-state button {
  background-color: #4e73df;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.3s;
}

.empty-state button:hover {
  background-color: #2e59d9;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40px;
  flex-wrap: wrap;
  gap: 10px;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.pagination button {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.pagination button:hover:not(:disabled) {
  background-color: #4e73df;
  color: white;
  border-color: #4e73df;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination button.active {
  background-color: #4e73df;
  color: white;
  border-color: #4e73df;
}

.page-info {
  margin-left: 15px;
  color: #6e707e;
  font-size: 0.95rem;
}

@media (max-width: 768px) {
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }

  .header-section h1 {
    font-size: 2rem;
  }

  .filters-section {
    flex-direction: column;
  }

  .search-box, .category-filter {
    width: 100%;
    max-width: none;
  }

  .product-image {
    height: 180px;
  }

  .pagination {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .pagination button {
    width: 100%;
    margin: 5px 0;
  }

  .page-info {
    margin: 15px 0 0;
    text-align: center;
  }
}
</style>